package com.example.designpatterns.strategy.payment;

import java.util.ArrayList;
import java.util.List;

/**
 * 购物车 - 使用支付策略的上下文
 */
public class ShoppingCart {
    private List<Item> items;
    private PaymentStrategy paymentStrategy;
    
    /**
     * 创建购物车
     */
    public ShoppingCart() {
        this.items = new ArrayList<>();
    }
    
    /**
     * 设置支付策略
     * @param paymentStrategy 支付策略
     */
    public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }
    
    /**
     * 添加商品到购物车
     * @param item 商品
     */
    public void addItem(Item item) {
        items.add(item);
    }
    
    /**
     * 移除商品
     * @param item 要移除的商品
     */
    public void removeItem(Item item) {
        items.remove(item);
    }
    
    /**
     * 计算购物车总金额
     * @return 总金额
     */
    public double calculateTotal() {
        return items.stream()
                .mapToDouble(item -> item.getPrice() * item.getQuantity())
                .sum();
    }
    
    /**
     * 使用设定的支付策略完成支付
     * @return 支付是否成功
     */
    public boolean checkout() {
        if (paymentStrategy == null) {
            throw new IllegalStateException("未设置支付方式");
        }
        
        double total = calculateTotal();
        System.out.println("\n结算购物车...");
        System.out.println("商品清单:");
        for (Item item : items) {
            System.out.println(" - " + item.getName() + " x" + item.getQuantity() 
                    + ": ¥" + (item.getPrice() * item.getQuantity()));
        }
        System.out.println("总计: ¥" + total);
        System.out.println("支付方式: " + paymentStrategy.getName());
        
        return paymentStrategy.pay(total);
    }
    
    /**
     * 购物车中的商品类
     */
    public static class Item {
        private String name;
        private double price;
        private int quantity;
        
        /**
         * 创建商品
         * @param name 商品名称
         * @param price 商品单价
         * @param quantity 商品数量
         */
        public Item(String name, double price, int quantity) {
            this.name = name;
            this.price = price;
            this.quantity = quantity;
        }
        
        public String getName() {
            return name;
        }
        
        public double getPrice() {
            return price;
        }
        
        public int getQuantity() {
            return quantity;
        }
    }
} 